package com.example.allshengmedical.experimentrun.activity;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.allsheng.widget.ShowFinishDialog;
import com.allsheng.widget.AllShengDialog.ClickListenerInterface;
import com.allsheng.widget.ShowFinishDialog.MyClickListenerInterface;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentanalyze.activity.AnalyzeAmplificationplotActivity;
import com.example.allshengmedical.experimentnew.bean.FileBean;
import com.example.allshengmedical.experimentnew.bean.LayoutTableBean;
import com.example.allshengmedical.experimentnew.bean.MethodBean;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.util.FileManagerUtil;
import com.example.allshengmedical.util.MyHorizontalScrollView;
import com.example.allshengmedical.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itboye.allshengmedical.sci.DefaultSerialControl;
import com.itboye.allshengmedical.sci.ISerialControl;
import com.itboye.allshengmedical.sci.cmd.req.CmdType;
import com.itboye.allshengmedical.sci.packet.resp.BaseRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.DetectLightIntensitTempRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.GetTempRespPacket;
import com.itextpdf.text.xml.xmp.LangAlt;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

//运行的服务
public class RunMethodService extends Service {
	boolean isTest = false;
	int thridHunder = 0;
	// 数据
	String folderName;
	String fileName;
	private String appFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical";
	StringBuffer contextString = new StringBuffer();

	// 曲线图
	// 上半部
	private ArrayList<MethodBean> activityMethodBeans;

	// 下半部分
	private String editTextString;

	// 下面的图表
	HashMap<Integer, Integer> pointMap = new HashMap();
	List<HashMap<String, Object>> pointMaps = new ArrayList<HashMap<String, Object>>();

	// 下面的横划
	MyHorizontalScrollView downScrollView, upScrollView;

	// 进度条
	// private Handler mhanHandler;
	ISerialControl controlInstance;
	SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");
	TimeCountUtils count = new TimeCountUtils();
	int nowtime, nowtime2;
	final int ProgressSatus = 31000;
	final int timeSatus = 31001;
	final int NowTimeSatus = 30003;
	int saveTemp = 0;// 从文件中获取的保存温度(一般为4度)
	double nowTemp = 0;// 当前模块1实时温度
	double mode2NowTemp = 0;// 当前模块2实时温度
	double mode3NowTemp = 0;// 当前模块3实时温度
	double TempUpCoefficient = 440f;// 温度升温系数*1000
	double TempDownCoefficient = 440f;// 温度降温系数*1000
	double HotTempUpCoefficient = 1000f;// 热盖升温系数*1000
	double ProgressSpeed = 0;// 进度条进度
	double StartHotLid = 0;// 热盖初始温度
	String hotLidTemperature, sampleVolumeString, readDataString, fourduString, isholdingCheckBoxSelect;
	String passReferenceString;// passReference
	int cmdindex = 0;// 当前第几步
	boolean ishaveDelt = false;// 是否有溶解度
	boolean isPhotoing = false;// 是否在拍照
	boolean isFirst = true;// 是否发送第一个目标指令
	boolean isFirstGetTemp = true;// 是否是第一次获取温度
	boolean isFirstTargetTemp = false;// 是否是第一次到目标温度
	boolean isFirstDelt = true;// 是否是第一次进入溶解度
	boolean isCircleEnd = true;// 扩增结束
	boolean isStartDelt = false;// 是否开始溶解度
	boolean isHaveFourTemp = false;// 是否有四度保存
	boolean isInterrupt = false;// 线程是否结束（是否有停止）
	boolean isSaveAll = true;//
	boolean isFlag = true;// 结束试验后达到停止温度的标志
	boolean isHaveChangePhotoCount = false;// 是否改变循环次数
	boolean isDestory = false;// service是否destory
	boolean isAllStepEnd = false;// 所有步骤完成
	boolean isSaveTempData = true;// 是否保存温度
	boolean isHavePhoto = false;// 是否有拍照
	List<LayoutTableBean> activityLayoutTableBeans = new ArrayList<LayoutTableBean>();
	ArrayList<String> channelList = new ArrayList<String>();
	int channelSize = 0;// 要有多少次检测溶解度
	int deletIndex = 0;// 加第几个溶解度delt
	int channelIndex = 0;// 共检查多少次
	int rightPhotoCount = 0;// 扩增拍照拍了几次
	int deltPhotoCount = 0;// 溶解度拍了几次
	double tragetTemp;// 下次目标温度
	double deletT = 0;// 溶解度
	// HashMap<Integer, ArrayList<ArrayList<Float>>> photoarrayList = new
	// HashMap<Integer, ArrayList<ArrayList<Float>>>();
	Thread experimentThread;// 实验流程线程
	String deletcontent;
	TempDBHelper tempDBHelper;
	ServiceMethodUtils MethodClass = new ServiceMethodUtils();
	DeletDBHelper deletDBhelper;
	AmplifucationDBHelper amplifucationDBHelper;
	AmplifucationActivity amplifucationActivity;
	double targetDeletTemp = 0;
	// int rightSelect = 0;
	int repititions = 0;
	int getRepititions = 0;
	long systemStartTime = 0;
	long changePhotoCount = 0;
	CommonSQLiteHelper commonSQLiteHelper;
	boolean stopByUser = false;

	Boolean saveBoo = false;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		commonSQLiteHelper = new CommonSQLiteHelper(BaseApplication.getContext());
		commonSQLiteHelper.delete();// 删除上次数据库
		commonSQLiteHelper.open();
		SharedPreferences photopreferences = getSharedPreferences("photoBackCount", Context.MODE_PRIVATE);
		Editor photoeditor = photopreferences.edit();
		photoeditor.putString("phototime_count", 0 + "");
		photoeditor.commit();
		tempDBHelper = new TempDBHelper(RunMethodService.this);
		deletDBhelper = new DeletDBHelper(this);
		amplifucationDBHelper = new AmplifucationDBHelper(this);
		// 打开端口
		controlInstance = DefaultSerialControl.getInstance();
		controlInstance.init();
		controlInstance.start();
		controlInstance.setHandler(mHandler);
		MethodClass.getInfo(appFilePath, contextString);
		initSimpleLineChartView();
		ChannelNum();
		IntentFilter filter = new IntentFilter("StopService");
		registerReceiver(receiver, filter);
		IntentFilter changePhotoBackCountfilter = new IntentFilter("changePhotoBackCount");
		registerReceiver(changePhotoBackCountreceiver, changePhotoBackCountfilter);
		experimentThread = new Thread(experimentRunable);
		experimentThread.start();
		SharedPreferences preferences = getSharedPreferences("ExperimentFinish", Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.putBoolean("isFinish", false);
		editor.commit();
		SharedPreferences tempPreferences = getSharedPreferences("Temp", Context.MODE_PRIVATE);
		Editor tempeditor = tempPreferences.edit();
		tempeditor.putString("tempMod1", "0");
		tempeditor.putString("tempMod2", " 0");
		tempeditor.putString("tempMod3", "0");
		tempeditor.putString("step", cmdindex + "");
		tempeditor.commit();
	}

	// 計算改變循环次数后的时间
	BroadcastReceiver changePhotoBackCountreceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			isHaveChangePhotoCount = true;
			getRepititions = Integer.parseInt(intent.getStringExtra("changePhotoBackCount")) - 1;
			changePhotoCount = (long) MethodClass.changePhotoCountTime(activityMethodBeans, TempUpCoefficient,
					TempDownCoefficient, HotTempUpCoefficient, Double.parseDouble(hotLidTemperature.trim()),
					StartHotLid, nowTemp, channelList.size(), getRepititions + 1);
			int time = (int) (changePhotoCount - MethodClass.getTime(activityMethodBeans, TempUpCoefficient,
					TempDownCoefficient, HotTempUpCoefficient, Double.parseDouble(hotLidTemperature.trim()),
					StartHotLid, nowTemp, channelList.size()));
			nowtime += time;
			SharedPreferences sharedPreferences = getSharedPreferences("Time", Context.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			editor.putString("endTime",
					sdfDate.format(systemStartTime + MethodClass.getTime(activityMethodBeans, TempUpCoefficient,
							TempDownCoefficient, HotTempUpCoefficient, Double.parseDouble(hotLidTemperature.trim()),
							StartHotLid, nowTemp, channelList.size()) + time));
			editor.commit();
		}

	};
	// 接受到停止的广播
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			
			if(isHaveFourTemp){
				if (isFlag) {
					isFlag = false;
					controlInstance.addCommand(CmdType.FinishExpriment, null, 0);

					SystemClock.sleep(1000);
					isFlag = false;
					Intent finishintent = new Intent("ExperimentFinish");
					sendBroadcast(finishintent);
					SharedPreferences preferences = getSharedPreferences("ExperimentFinish", Context.MODE_PRIVATE);
					Editor editor = preferences.edit();
					editor.putBoolean("isFinish", true);
					editor.commit();
					isFirstGetTemp = true;
					controlInstance.pause();
					
				}
			
			// 弹出弹窗，去分析或回主页
			final ShowFinishDialog showFinishDialog = new ShowFinishDialog(BaseApplication.getContext(),
					"主页", "分析", "", isInterrupt);
			showFinishDialog.setClicklistener(new MyClickListenerInterface() {

				@Override
				public void Main() {
					// TODO Auto-generated method stub
					BaseApplication.getInstance().finishAll();
					Intent intent = new Intent(BaseApplication.getContext(), MainMenuActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					showFinishDialog.dismiss();
					stopSelf();
				}

				@Override
				public void Dis() {
					// TODO Auto-generated method stub
					Log.e("hu..........", "click");
					// Intent intent = new
					// Intent(BaseApplication
					// .getContext(),
					// AmplifucationActivity.class);
					// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					// startActivity(intent);
					showFinishDialog.dismiss();
					stopSelf();
				}

				@Override
				public void Anyalse() {
					// TODO Auto-generated method stub
					BaseApplication.getInstance().finishAll();
					Intent intent = new Intent(BaseApplication.getContext(),
							AnalyzeAmplificationplotActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					showFinishDialog.dismiss();
					stopSelf();
				}
			});
			showFinishDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			if (null == showFinishDialog || !showFinishDialog.isShowing()) {
				showFinishDialog.show();
			}
			
			}
			isInterrupt = true;
			isHaveFourTemp = false;
			stopByUser = true;
		}
	};
	// 接收端口返回数据
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case ISerialControl.FindPacketMessage:
				// 完成主界面更新,拿到数据
				update(msg.getData());
				break;
			case NowTimeSatus:
				// 进度条进度和剩余时间
				Intent Progressintent = new Intent("ProgressSpeed");
				Progressintent.putExtra("Progress", msg.arg1 + "");
				Progressintent.putExtra("NowTime", TimeCountUtils.secToTime(nowtime) + "");
				sendBroadcast(Progressintent);
				break;
			case ISerialControl.SCTimeoutMessage:
				// 超时的类型，系统设置里的超时也若有要求可以按此更改
				String cmdType = msg.getData().getString("cmdType");
				if (cmdType.length() < 1)
					return;
				// 根据type 转换packet 为你想要的
				CmdType type = CmdType.getCmdType(cmdType.substring(1));
				// 发送指令后这里会收到数据
				Log.d("hu timeout", "type=" + cmdType + type.toDesc());
				switch (type) {
				case DetectLightIntensitTemp:
					controlInstance.addCommand(CmdType.DetectLightIntensitTemp, null,
							Integer.parseInt(channelList.get(channelIndex)));

				}
				break;
			}
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}

	private void initSimpleLineChartView() {
		editTextString = contextString.substring(contextString.indexOf(",,Methods,,"), contextString.length());

		// mSimpleLineChart = (SimpleLineChart)
		// findViewById(R.id.simpleLineChart);
		activityMethodBeans = new ArrayList<MethodBean>();

		int index = editTextString.indexOf("Methods");
		// 上面解析
		while (!(editTextString.indexOf("steptType:", index) <= 0)) {

			// steptType:
			String steptType;
			steptType = editTextString.substring(editTextString.indexOf("steptType:", index) + 10,

					editTextString.indexOf(",temperature:", index));

			// LogUtil.e(steptType);

			// temperature
			String temperature;
			temperature = editTextString.substring(editTextString.indexOf(",temperature:", index) + 13,

					editTextString.indexOf(",time:", index));

			// LogUtil.e(temperature);
			// time
			String time;
			time = editTextString.substring(editTextString.indexOf(",time:", index) + 6,

					editTextString.indexOf(",goTo:", index));
					// LogUtil.e(time);

			// goTo
			String goTo;
			goTo = editTextString.substring(editTextString.indexOf(",goTo:", index) + 6,

					editTextString.indexOf(",Repititions:", index));
			// LogUtil.e(goTo);
			// Repititions
			String repititions;
			repititions = editTextString.substring(editTextString.indexOf(",Repititions:", index) + 13,

					editTextString.indexOf(",deltaT:", index));
			// LogUtil.e(repititions);
			// deltaT
			String deltaT;
			deltaT = editTextString.substring(editTextString.indexOf(",deltaT:", index) + 8,

					editTextString.indexOf(",rightSelect:", index));
			// LogUtil.e(deltaT);

			int nextIndex = editTextString.indexOf("steptType:", index) + 10;

			// rightSelect
			Boolean rightSelect;

			if (editTextString.indexOf(",steptType:", nextIndex) < 0) {
				rightSelect = Boolean
						.parseBoolean(editTextString.substring(editTextString.indexOf(",rightSelect:", index) + 13,
								editTextString.indexOf(",,pointMap", index)).trim());
				if ("null".equals(rightSelect)) {
					rightSelect = false;
				}

			} else {
				rightSelect = Boolean
						.parseBoolean(editTextString.substring(editTextString.indexOf(",rightSelect:", index) + 13,

								editTextString.indexOf(",steptType:", nextIndex)).trim());
				if ("null".equals(rightSelect)) {
					rightSelect = false;
				}
			}
			// LogUtil.e(rightSelect);
			index = editTextString.indexOf(",rightSelect:", index) + 13;
			hotLidTemperature = contextString.substring(contextString.indexOf("hotLidTemperature:") + 18,
					contextString.indexOf(",sampleVolumeString:"));
			sampleVolumeString = contextString.substring(contextString.indexOf("sampleVolumeString:") + 19,
					contextString.indexOf(",readDataString:"));
			readDataString = contextString.substring(contextString.indexOf("readDataString:") + 15,
					contextString.indexOf(",,", contextString.indexOf("readDataString:")));
			fourduString = contextString.substring(contextString.indexOf("fourduString:") + 13,
					contextString.indexOf(",hotLidTemperature:")).trim();
			isholdingCheckBoxSelect = contextString
					.substring(contextString.indexOf("holdingCheckBox:") + 16, contextString.indexOf(",fourduString:"))
					.trim();
			activityMethodBeans.add(new MethodBean(steptType.trim(), temperature.trim(), time.trim(), goTo.trim(),
					repititions.trim(), deltaT.trim(), rightSelect));
			if (isholdingCheckBoxSelect.equals("false")) {
				isHaveFourTemp = false;
			} else {
				isHaveFourTemp = true;
				saveTemp = Integer.parseInt(fourduString);
			}
		}
	}

	private  void update(Bundle bundle) {
		// TODO Auto-generated method stub
		Long startTime = System.currentTimeMillis();
		

		String cmdType = bundle.getString("cmdType");
		BaseRespPacket packet = (BaseRespPacket) bundle.getSerializable("packet");
		if (cmdType.length() < 1)
			return;
		// 根据type 转换packet 为你想要的
		CmdType type = CmdType.getCmdType(cmdType.substring(1));
		// 发送指令后这里会收到数据
		Log.d("read_data", "接受到的响应数据包是" + cmdType + type.toDesc());
		switch (type) {
		case GetTemp:
			// 得到的温度数据
			GetTempRespPacket tempResp = new GetTempRespPacket(packet);
			// 第一次得到温度，根据模块1和模块3的温度从而计算剩余时间
			if (isFirstGetTemp) {
				getTime(tempResp);
				isFirstGetTemp = false;
				StartHotLid = Double.parseDouble(tempResp.ModeThree());
			}
			transtDate(tempResp);// 传递温度数据
			// 有4度保存
			if (isHaveFourTemp) {
				if (!isSaveAll && (nowTemp <= (saveTemp))) {

					Log.e("hu", "4c结束实验");
					
				}
			} else {
				// 保存完所有数据并且温度达到设置的温度
				if (saveBoo && isAllStepEnd && nowTemp <= 30) {// 小于三十度结束，但是快到30度时会很慢
					Log.e("hu", "结束实验");

					if (isFlag) {
						controlInstance.addCommand(CmdType.FinishExpriment, null, 0);

						SystemClock.sleep(1000);
						isFlag = false;
						Intent finishintent = new Intent("ExperimentFinish");
						sendBroadcast(finishintent);
						SharedPreferences preferences = getSharedPreferences("ExperimentFinish", Context.MODE_PRIVATE);
						Editor editor = preferences.edit();
						editor.putBoolean("isFinish", true);
						editor.commit();
						isFirstGetTemp = true;

						// 弹出弹窗，去分析或回主页
						final ShowFinishDialog showFinishDialog = new ShowFinishDialog(BaseApplication.getContext(),
								"主页", "分析", "", isInterrupt);
						showFinishDialog.setClicklistener(new MyClickListenerInterface() {

							@Override
							public void Main() {
								// TODO Auto-generated method stub
								BaseApplication.getInstance().finishAll();
								Intent intent = new Intent(BaseApplication.getContext(), MainMenuActivity.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(intent);
								showFinishDialog.dismiss();
								stopSelf();
							}

							@Override
							public void Dis() {
								// TODO Auto-generated method stub
								Log.e("hu..........", "click");
								// Intent intent = new
								// Intent(BaseApplication
								// .getContext(),
								// AmplifucationActivity.class);
								// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								// startActivity(intent);
								showFinishDialog.dismiss();
								stopSelf();
							}

							@Override
							public void Anyalse() {
								// TODO Auto-generated method stub
								BaseApplication.getInstance().finishAll();
								Intent intent = new Intent(BaseApplication.getContext(),
										AnalyzeAmplificationplotActivity.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(intent);
								showFinishDialog.dismiss();
								stopSelf();
							}
						});
						showFinishDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
						if (null == showFinishDialog || !showFinishDialog.isShowing()) {
							showFinishDialog.show();
						}
					}
				}

			}
		
			Long endTime = System.currentTimeMillis();
			System.out.println(endTime -startTime + "温度数据传输所需时间所需时间");
			break;
		// 光强数据
		case DetectLightIntensitTemp:
//			DetectLightIntensitTempRespPacket pack = new DetectLightIntensitTempRespPacket(packet);
//
//			// pack.returnData();
//
//			// channel - line - point
//			Log.e("hu msg", !ishaveDelt + ",cmdindex" + cmdindex);
//			// if (cmdindex < activityMethodBeans.size()) {
//			if (!isStartDelt) {// 拍照光强
//				Log.e("hu msg", "拍照光强" + rightPhotoCount);
//				// 发送光强数据到am页面中
//				Intent paintBrocast = new Intent("paintDate");
//				paintBrocast.putExtra("content", pack.returnData());
//				paintBrocast.putExtra("channelIndex", Integer.parseInt(channelList.get(channelIndex)));
//				paintBrocast.putExtra("photoCount", rightPhotoCount);
//				paintBrocast.putExtra("channelSize", channelList.size() + "");
//				sendBroadcast(paintBrocast);
//			} else {// 溶解度光强
//				Log.e("hu msg", "溶解度光强");
//				// 保存数据到溶解度数据库中
//				deletLight(pack);
//				Intent paintBrocast = new Intent("RongjiepaintDate");
//				paintBrocast.putExtra("photoCount", deltPhotoCount);
//				paintBrocast.putExtra("channelSize", channelList.size() + "");
//				paintBrocast.putExtra("channelList", channelList);
//				paintBrocast.putExtra("channelIndex", channelList.get(channelIndex) + "");
//				paintBrocast.putExtra("time1", System.currentTimeMillis() +"");
//				sendBroadcast(paintBrocast);
//
//			}
//			// }
//			channelIndex++;
//			// channelList.size()几个通道，若还有通道未检测完接着检测光强并发检测几通道的指令
//			if (channelIndex < channelList.size()) {
//				controlInstance.addCommand(CmdType.DetectLightIntensitTemp, null,
//						Integer.parseInt(channelList.get(channelIndex)));
//			} else {
//				channelIndex = 0;// 通道检测完全重新置零
//				// 如果有溶解度光强并计算下次的温度
//				if (ishaveDelt && deletIndex < channelSize) {
//					int nextMode1Traget = (int) ((Double
//							.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature()) + deletIndex * deletT
//							+ 0.05) * 10);
//					int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
//
//					controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
//
//				} else {
//					// Log.e("hu", "拍照后下次"+ "activityMeth"+
//					// activityMethodBeans.get(cmdindex).getDeltaT() +
//					// activityMethodBeans.get(cmdindex).getRightSelect());
//					if (cmdindex < activityMethodBeans.size()
//							&& TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getDeltaT())) {
//
//						// 计算下次的温度
//						tragetTemp = Double.parseDouble(activityMethodBeans.get(cmdindex).getTemperature());
//						Log.e("hu", "拍照后下次温度" + tragetTemp);
//						int nextMode1Traget = (int) (tragetTemp) * 10;
//						int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
//						controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
//					}
//				}
//				isPhotoing = false;
//				Log.e("hu", "拍照完了");
//			}
//			Long endTime2 = System.currentTimeMillis();
//			System.out.println(endTime2
//					-startTime + "光强传输所需时间所需时间");
			new DetectLightIntensitTempTask().execute(packet);
			Long endTime2 = System.currentTimeMillis();
			System.out.println(endTime2
					-startTime + "光强传输所需时间所需时间");
			break;
		
		}
	};
	class DetectLightIntensitTempTask extends AsyncTask<BaseRespPacket , String, String>{

		@Override
		protected String doInBackground(BaseRespPacket... params) {
			// TODO Auto-generated method stub
			
			DetectLightIntensitTempRespPacket pack = new DetectLightIntensitTempRespPacket(params[0]);

			// pack.returnData();

			// channel - line - point
			Log.e("hu msg", !ishaveDelt + ",cmdindex" + cmdindex);
			// if (cmdindex < activityMethodBeans.size()) {
			if (!isStartDelt) {// 拍照光强
				Log.e("hu msg", "拍照光强" + rightPhotoCount);
				// 发送光强数据到am页面中
				Intent paintBrocast = new Intent("paintDate");
				paintBrocast.putExtra("content", pack.returnData());
				paintBrocast.putExtra("channelIndex", Integer.parseInt(channelList.get(channelIndex)));
				paintBrocast.putExtra("photoCount", rightPhotoCount);
				paintBrocast.putExtra("channelSize", channelList.size() + "");
				sendBroadcast(paintBrocast);
			} else {// 溶解度光强
				Log.e("hu msg", "溶解度光强");
				// 保存数据到溶解度数据库中
				deletLight(pack);
				Intent paintBrocast = new Intent("RongjiepaintDate");
				paintBrocast.putExtra("photoCount", deltPhotoCount);
				paintBrocast.putExtra("channelSize", channelList.size() + "");
				paintBrocast.putExtra("channelList", channelList);
				paintBrocast.putExtra("channelIndex", channelList.get(channelIndex) + "");
				paintBrocast.putExtra("time1", System.currentTimeMillis() + "");
				sendBroadcast(paintBrocast);

			}
			// }
			channelIndex++;
			// channelList.size()几个通道，若还有通道未检测完接着检测光强并发检测几通道的指令
			if (channelIndex < channelList.size()) {
				controlInstance.addCommand(CmdType.DetectLightIntensitTemp, null,
						Integer.parseInt(channelList.get(channelIndex)));
			} else {
				channelIndex = 0;// 通道检测完全重新置零
				// 如果有溶解度光强并计算下次的温度
				if (ishaveDelt && deletIndex < channelSize) {
					int nextMode1Traget = (int) ((Double
							.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature()) + deletIndex * deletT
							+ 0.05) * 10);
					int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;

					controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);

				} else {
					// Log.e("hu", "拍照后下次"+ "activityMeth"+
					// activityMethodBeans.get(cmdindex).getDeltaT() +
					// activityMethodBeans.get(cmdindex).getRightSelect());
					if (cmdindex < activityMethodBeans.size()
							&& TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getDeltaT())) {

						// 计算下次的温度
						tragetTemp = Double.parseDouble(activityMethodBeans.get(cmdindex).getTemperature());
						Log.e("hu", "拍照后下次温度" + tragetTemp);
						int nextMode1Traget = (int) (tragetTemp) * 10;
						int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
						controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
					}
				}
				isPhotoing = false;
				Log.e("hu", "拍照完了");
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
		}
	}
	// 保存三个温度数据到数据库中，通过广播和sharepreference保存数据（拍照时不设置和获取温度，所以需要保存到本地）
	public void transtDate(GetTempRespPacket tempResp) {
		nowTemp = Double.parseDouble(tempResp.ModeOne());
		mode3NowTemp = Double.parseDouble(tempResp.ModeThree());
		Log.e("hu", nowTemp + "");
		Intent Tempintent = new Intent("TempDate");
		Tempintent.putExtra("temp", (nowTemp + ""));
		Tempintent.putExtra("tempMod1", tempResp.ModeOne());
		Tempintent.putExtra("tempMod2", tempResp.ModeTwo());
		Tempintent.putExtra("tempMod3", tempResp.ModeThree());
		Tempintent.putExtra("step", cmdindex + "");
		sendBroadcast(Tempintent);
		SharedPreferences tempPreferences = getSharedPreferences("Temp", Context.MODE_PRIVATE);
		Editor editor = tempPreferences.edit();
		editor.putString("tempMod1", tempResp.ModeOne());
		editor.putString("tempMod2", tempResp.ModeTwo());
		editor.putString("tempMod3", tempResp.ModeThree());
		editor.putString("step", cmdindex + "");
		editor.commit();
		mode2NowTemp = Double.parseDouble(tempResp.ModeTwo());
		if (tempResp.ModeOne() != null && !isDestory) {
			tempDBHelper.add(tempResp.ModeOne(), tempResp.ModeTwo(), tempResp.ModeThree());
		} else if (!isDestory) {
			SharedPreferences preferences = getSharedPreferences("Temp", Context.MODE_PRIVATE);
			tempDBHelper.add(preferences.getString("tempMod1", "0"), preferences.getString("tempMod2", "0"),
					preferences.getString("tempMod3", "0"));
		}

	}

	// 解析溶解度光强并保存到数据库中
	private void deletLight(final DetectLightIntensitTempRespPacket pack) {

		// TODO Auto-generated method stub
		deletcontent = pack.returnData();

		int index = 0;

		// 通道号 channelIndex+1
		for (int i = 0; i < 32; i++) {

			// 点
			deletDBhelper.add(channelList.get(channelIndex),
					deletcontent.substring(index, deletcontent.indexOf(",", index)), (i) + "", deltPhotoCount + "");
			index = deletcontent.indexOf(",", index) + 1;
			// SystemClock.sleep(1);
		}

	}

	// 计算共有几个通道数量
	private void ChannelNum() {
		int index = 0;
		activityLayoutTableBeans = new ArrayList<LayoutTableBean>();
		while (!(contextString.indexOf("Aisle", index) <= 0)) {
			String aisle;
			aisle = contextString.substring(contextString.indexOf(",Aisle", index) + 7,

					contextString.indexOf(",Color", index));
			// LogUtil.e(aisle);
			String color;
			color = contextString.substring(contextString.indexOf(",Color", index) + 7,

					contextString.indexOf(",Target", index));
					// LogUtil.e(color);

			// Target
			String target;
			target = contextString.substring(contextString.indexOf(",Target", index) + 8,

					contextString.indexOf(",Dyes", index));

			// LogUtil.e(target);

			int nextIndex = contextString.indexOf(",Aisle", index) + 7;

			// Dyes
			String dyes;
			if (contextString.indexOf(",Aisle", nextIndex) < 0) {

				dyes = contextString.substring(contextString.indexOf(",Dyes", index) + 6,
						contextString.indexOf(",,dataSourceListBlock1", index));

				// LogUtil.e(dyes);
			} else {

				dyes = contextString.substring(contextString.indexOf(",Dyes", index) + 6,

						contextString.indexOf(",Aisle", nextIndex));
				// LogUtil.e(dyes);
			}

			index = contextString.indexOf(",Dyes", index) + 5;

			activityLayoutTableBeans.add(new LayoutTableBean(false, Integer.parseInt(aisle.trim()),
					Integer.parseInt(color.trim()), target, dyes));
		}
		ArrayList<Boolean> boos = new ArrayList<Boolean>();
		boos.add(false);
		boos.add(false);
		boos.add(false);
		boos.add(false);
		for (LayoutTableBean bean : activityLayoutTableBeans) {
			if (bean.getAisle() == 1) {
				boos.set(0, true);
			} else if (bean.getAisle() == 2) {
				boos.set(1, true);
			} else if (bean.getAisle() == 3) {
				boos.set(2, true);
			} else if (bean.getAisle() == 4) {
				boos.set(3, true);
			}

		}
		for (int i = 0; i < boos.size(); i++) {
			if (i == 0 && MethodClass.whichChannel(contextString) != null) {
				channelList.add(MethodClass.whichChannel(contextString));
			}
			if (boos.get(i)) {
				channelList.add(i + 1 + "");
			} else {

			}
		}

	}

	// 计算开始时间和结束时间（保存到本地），启动倒计时线程
	private void getTime(GetTempRespPacket tempResp) {
		double time = MethodClass.getTime(activityMethodBeans, TempUpCoefficient, TempDownCoefficient,
				HotTempUpCoefficient, Double.parseDouble(hotLidTemperature.trim()), StartHotLid, nowTemp,
				channelList.size());
		AllTimeCountDown((int) time);
		SharedPreferences sharedPreferences = getSharedPreferences("Time", Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		systemStartTime = System.currentTimeMillis();
		editor.putString("startTime", sdfDate.format(systemStartTime));
		editor.putString("endTime", sdfDate.format(systemStartTime + time));
		editor.commit();
	}

	// 倒计时线程，并计算进度条进度和剩余时间
	public void AllTimeCountDown(final int time) {

		Thread Timethread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				nowtime = time;
				while (isFlag) {
					if (isInterrupt) {
						break;
					}
					if (nowtime > 1000) {// 结束
						SystemClock.sleep(1000);
						nowtime = nowtime - 1000;
						if (isHaveChangePhotoCount) {
							ProgressSpeed = ((double) nowtime / (double) changePhotoCount);
						} else {
							ProgressSpeed = ((double) nowtime / (double) time);
						}

						Message message = new Message();
						message.what = NowTimeSatus;
						message.arg1 = (int) ((-ProgressSpeed + 1) * 100);
						mHandler.sendMessageDelayed(message, 0);
					} else {
						nowtime = 1000;
						SystemClock.sleep(1000);
						Message message = new Message();
						message.what = NowTimeSatus;
						message.arg1 = 99;
						mHandler.sendMessageDelayed(message, 0);
					}
				}

			}
		});
		Timethread.start();
	}

	// 实验流程线程
	Runnable experimentRunable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (!isDestory) {
				Long startTime = System.currentTimeMillis();
				TranstanCmd();
				Long endTime = System.currentTimeMillis();
				System.out.println(endTime -startTime + "实验流程线程While所需时间");
			}

		}
	};

	public synchronized void TranstanCmd() {

		while (cmdindex < activityMethodBeans.size()) {
			Long startTime = System.currentTimeMillis();
			// 如果拍照完，点击停止或所有步骤结束就break掉
			if (!isPhotoing && (isInterrupt || isAllStepEnd)) {
				break;
			} // 非拍照状态下获取当前温度
			if (!isPhotoing) {
				controlInstance.addCommand(CmdType.GetTemp, null, 0);
			} else {
				Intent Tempintent = new Intent("TempDate");
				Tempintent.putExtra("temp", (nowTemp + ""));
				Tempintent.putExtra("tempMod3", mode3NowTemp);
				Tempintent.putExtra("step", cmdindex + "");
				sendBroadcast(Tempintent);
			}
			// if (isPhotoing) {
			// continue;
			// }
			// 如果已经开始溶解度或满足alltrue里的条件
			if (ishaveDelt || isAllTrue()) {
				// 判断是否有溶解曲线，如果有就开；
				if (cmdindex < activityMethodBeans.size()
						&& !TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getDeltaT())) {
					if (isFirstDelt) {// 第一次开溶解度时发送一条指令
						Log.e("hu", "开溶解曲线");
						controlInstance.addCommand(CmdType.RunCmd, null, 0);
						SystemClock.sleep(100);
						isFirstDelt = false;

					}

					ishaveDelt = true;
					deletT = Double.parseDouble(activityMethodBeans.get(cmdindex).getDeltaT().trim());
					deletTempCmd();// 溶解度方法
				}
			}
			Long endTime = System.currentTimeMillis();

			System.out.println(endTime -startTime + "线程里里While所需时间");
			SystemClock.sleep(1000);

		}
		// 结束了(如果有4度则不发)实验流程步骤已全部走完，开始保存数据
		if (!isPhotoing) {
			while (isFlag) {
				isAllStepEnd = true;
				if (!isPhotoing) {
					if (isSaveAll) {
						// Thread saveThread = new Thread(new Runnable() {
						//
						// @Override
						// public synchronized void run() {
						// // TODO Auto-generated method stub
						if (isHavePhoto) {// 扩增数据
							MethodClass.saveLightDate(appFilePath, amplifucationDBHelper, contextString);
						}
						if (isStartDelt) {// 溶解度数据
							MethodClass.saveDeletLightDate(activityMethodBeans, deletDBhelper, appFilePath, true,
									channelSize, contextString);
							isStartDelt = false;
						}
						if (isSaveTempData) {// 保存温度数据
							MethodClass.saveTempdate(appFilePath, tempDBHelper.query(),
									tempDBHelper.queryTempMode2Name(), tempDBHelper.queryTempMode3Name());
							isSaveTempData = false;

						}
						if (!isSaveTempData) {// 更改文件名
							updateFileName();
						}
						// }
						// });
						// saveThread.start();
						isSaveAll = false;
					}
					if (!isSaveAll) {
						if (!isHaveFourTemp) {// 没4度保存发送30度降温
							Log.e("hu", "结束了");
							if (nowTemp > 45) {// 有时会不发，所以大于45度时都发送目标温度
								controlInstance.addCommand(CmdType.SetTemp, null, 250, 1050, 0, 0);// 本来应该是30度，但是接近到30时会很慢，所以目标温度为25，但是还是30停止
							}
						} else {// 4度保存发送4度降温
							controlInstance.addCommand(CmdType.SetTemp, null, saveTemp * 10, 1050, 0, 0);
						}
					}
					SystemClock.sleep(1000);
					// 获取当前温度
					controlInstance.addCommand(CmdType.GetTemp, null, 0);

				}
			}
		
		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub

		isDestory = true;
		isAllStepEnd = false;
		try {
			experimentThread.stop();
		} catch (Exception e) {
			// TODO: handle exception
		}
		Log.e("service", "service destory");
		mHandler.removeMessages(NowTimeSatus);
		mHandler.removeMessages(ISerialControl.FindPacketMessage);
		mHandler.removeMessages(ISerialControl.SCTimeoutMessage);
		controlInstance.pause();// 关闭端口
		// tempDBHelper.close();
		Intent Progressintent = new Intent("ProgressSpeed");
		Progressintent.putExtra("Progress", 100 + "");
		Progressintent.putExtra("NowTime", "00:00");
		sendBroadcast(Progressintent);
		super.onDestroy();

	}

	private synchronized boolean isAllTrue() {
		MethodBean bean = activityMethodBeans.get(cmdindex);
		if (!TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getRepititions())) {
			repititions = Integer.parseInt(activityMethodBeans.get(cmdindex).getRepititions()) - 1;
		} else {
			repititions = 0;
		}

		if (isFirst) {// 第一次进入发送目标指令
			controlInstance.addCommand(CmdType.RunCmd, null, 0);
			SystemClock.sleep(100);
			// 发送第一个目标指令
			int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
			controlInstance.addCommand(CmdType.SetTemp, null,
					(int) Double.parseDouble(activityMethodBeans.get(0).getTemperature()) * 10, nextMode3Traget, 0, 0);
			Log.e("hu", " 发送第一个目标指令");
			isFirst = false;

		}

		Log.e("hu", "当前index=" + cmdindex);
		if (isTest) {
			// 数据测试
			thridHunder++;
			tempDBHelper.add("" + 100, "200", "300");
			Intent intent = new Intent("TempDate");
			intent.putExtra("temp", 100 + "");
			intent.putExtra("tempMod3", 300 + "");
			sendBroadcast(intent);
			Intent paintBrocast = new Intent("paintDate");
			// paintBrocast.putExtra("lineArray", lineArray);
			String content = "4751,288142,3757,297643,3475,295346,3413,310624,4084,307598,4078,286539,3360,310190,3498,287512,3926,316789,3849,328266,3879,322429,3939,326913,3570,331819,3752,318723,3655,310438,3201,300300,";
			paintBrocast.putExtra("content", content);
			paintBrocast.putExtra("channelIndex", Integer.parseInt(channelList.get(channelIndex)));
			paintBrocast.putExtra("photoCount", thridHunder);
			sendBroadcast(paintBrocast);
			Intent RongjiepaintDate = new Intent("RongjiepaintDate");
			RongjiepaintDate.putExtra("photoCount", deltPhotoCount);
			RongjiepaintDate.putExtra("channelSize", channelList.size() + "");
			RongjiepaintDate.putExtra("channelList", channelList);
			sendBroadcast(RongjiepaintDate);

			int n = 1;
			while (n < 5) {
				int index = 0;
				for (int i = 0; i < 32; i++) {
					String s = content.substring(index, content.indexOf(",", index));
					deletDBhelper.add(channelList.get(channelIndex), s, n + "", thridHunder + "");
					index = content.indexOf(",", index) + 1;
				}
				n++;
				SystemClock.sleep(1000);

			}

			int x = 0;
			// while (x < 32) {
			// deletDBhelper.add(channelList.get(channelIndex),
			// content.substring(index, content.indexOf(",", index)),
			// x + "", thridHunder + "");
			// index = content.indexOf(",", index) + 1;
			// x++;
			// }
			if (thridHunder == 300) {
				ArrayList<Float> floats = new ArrayList<Float>();
				ArrayList<ArrayList<Float>> float1s = new ArrayList<ArrayList<Float>>();

				for (Float i = 0f; i < 116; i++) {
					floats.add((float) (60 + i * 0.3));

				}
				for (int i = 0; i < 32; i++) {
					float1s.add(floats);
				}

				// for (int i = 0; i < 5; i++) {
				// arrayListDeltTemp.put(
				// Integer.parseInt(channelList.get(channelIndex)),
				// float1s);
				// }
				// MethodClass.saveTempdate(appFilePath,
				// tempDBHelper.query(tempDBHelper.sqlDB()),
				// tempDBHelper.queryTempMode2Name(tempDBHelper.sqlDB()),
				// tempDBHelper.queryTempMode3Name(tempDBHelper.sqlDB()));
				// MethodClass.saveRawdata2(activityLayoutTableBeans,
				// appFilePath,
				// 120, contextString);
			}
			// endTest
		}

		Log.e("hu", bean.toString() + "是否有溶解=" + ishaveDelt + "now temp=" + nowTemp);
		// .replace("℃", ""))
		// 注意误差，误差太小或者太大，都有可能不会执行此方法
		Log.e("hu当前温度与目标温度的比较",
				nowTemp + "=当前,目标=" + Double.parseDouble(bean.getTemperature().replace("℃", "").trim()) + "");
		tragetTemp = Double.parseDouble(bean.getTemperature().replace("℃", "").trim());
		// 当前温度和目标温度温度差在0.1内，即达到目标温度
		if (Math.abs(
				(nowTemp + 0.05) - (Double.parseDouble(bean.getTemperature().replace("℃", "").trim()) + 0.05)) <= 0.1
				|| isFirstTargetTemp) {
			Log.e("hu", "目标温度=当前温度");
			ishaveDelt = false;
			isFirstTargetTemp = true;
			if (bean.getTargetTempTime() == 0) {
				Log.e("hu", " 倒计时开始");
				// 达到目标温度的时间
				bean.setTargetTempTime(System.currentTimeMillis());

			}
			// 倒计时完了，并拍照结束
			if (!isPhotoing
					&& System.currentTimeMillis() - bean.getTargetTempTime() >= count.TimeCalculation(bean.getTime())) {
				Log.e("hu", " 倒计时完了");
				isFirstTargetTemp = false;
				if (bean.getRightSelect()) {
					isHavePhoto = true;
					// 拍照的指令
					isPhotoing = true;
					rightPhotoCount++;
					channelIndex = 0;
					// 保存拍照次数到本地
					SharedPreferences photopreferences = getSharedPreferences("photoBackCount", Context.MODE_PRIVATE);
					Editor photoeditor = photopreferences.edit();

					if (rightPhotoCount == 0) {
						photoeditor.putString("phototime_count", rightPhotoCount + "");
					} else {
						photoeditor.putString("phototime_count", rightPhotoCount + "");

					}
					if (isHaveChangePhotoCount) {
						repititions = getRepititions;
					}
					photoeditor.commit();

					// SystemClock.sleep(100);
					// 发送拍照光强
					controlInstance.addCommand(CmdType.DetectLightIntensitTemp, null,
							Integer.parseInt(channelList.get(0)));

					Log.e("hu", " 拍照的指令");

				}
				Log.e("hugetBackCount", "getBackCount=" + bean.getBackCount() + ",repititions=" + repititions);
				// 没有goto或者当前循环等于需要循环的次数
				if ((TextUtils.isEmpty(bean.getGoTo()) || bean.getBackCount() == repititions)) {
					// 循环数置零和开始倒计时的时间置零
					bean.setBackCount(0);
					bean.setTargetTempTime(0);
					cmdindex++;
					Log.e("hu", " 循环完了");
					// 发送下次目标温度指令，获取光强那里也发（有可能处于拍照状态不会执行到这里）
					if (cmdindex < activityMethodBeans.size()) {
						if (!TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getDeltaT())) {
							int nextMode1Traget = (int) (Double
									.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature()) * 10);
							int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
							controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
						} else {
							if (!isPhotoing) {
								int nextMode1Traget = (int) (Double
										.parseDouble(activityMethodBeans.get(cmdindex).getTemperature()) * 10);
								int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;

								controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0,
										0);
								Log.e("hu", " 没循环下一次目标温度" + nextMode1Traget);
							} else {
								Log.e("hu...isphotn", "没循环");
							}

						}

					} else {
						isAllStepEnd = true;
						return false;
					}
					return true;
				} else {
					// if (!isPhotoing) {
					Log.e("hu循环第几次", "x循环第几次" + bean.getBackCount());
					bean.incBackCount();
					bean.setTargetTempTime(0);
					cmdindex = Integer.parseInt(bean.getGoTo()) - 1;
					// 下一次目标温度
					if (!TextUtils.isEmpty(activityMethodBeans.get(cmdindex).getDeltaT())) {
						int nextMode1Traget = (int) (Double
								.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature()) * 10);
						int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
						controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
					} else {
						if (!isPhotoing) {
							int nextMode1Traget = (int) (Double
									.parseDouble(activityMethodBeans.get(cmdindex).getTemperature()) * 10);
							int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
							controlInstance.addCommand(CmdType.SetTemp, null, nextMode1Traget, nextMode3Traget, 0, 0);
							Log.e("hu", " 循环下一次目标温度" + (int) (Double.parseDouble(bean.getTemperature()) * 10));
						}

					}

				}
			}
		}
		return false;
	}

	/**
	 * 
	 * @param isHave
	 *            是否开启
	 * @param deletT
	 *            温差 目标温度
	 */
	// 溶解度的流程，类似于前面的步骤
	public synchronized void deletTempCmd() {
		double stratDeletTemp = 0;
		stratDeletTemp = Double.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature().trim());
		targetDeletTemp = Double.parseDouble(activityMethodBeans.get(cmdindex).getTemperature().trim());
		channelSize = (int) ((Math.abs(((targetDeletTemp - stratDeletTemp)))) / deletT) + 1;
		isStartDelt = true;
		Log.e("hu.....", deletIndex + ",=deletIndex,channelSize=" + channelSize);
		if (!isPhotoing && deletIndex >= channelSize) {
			Log.e("hu", "超过了" + channelSize);
			ishaveDelt = false;
			int nextMode3Traget = (int) (Double.parseDouble(hotLidTemperature.trim())) * 10;
			controlInstance.addCommand(CmdType.SetTemp, null, (int) (targetDeletTemp) * 10, nextMode3Traget, 0, 0);
		}
		if (Math.abs((nowTemp - (Double.parseDouble(activityMethodBeans.get(cmdindex - 1).getTemperature().trim())
				+ deletIndex * deletT))) <= 0.01 && deletIndex < channelSize) {
			// SystemClock.sleep(10000);// 延时10s
			deletIndex++;
			isPhotoing = true;
			channelIndex = 0;
			deltPhotoCount++;
			Log.e("hu", deltPhotoCount + "=deltPhotoCount");
			controlInstance.addCommand(CmdType.DetectLightIntensitTemp, null, Integer.parseInt(channelList.get(0)));
		}

	}

	/**
	 * 更新文件名
	 * 
	 */
	public synchronized void updateFileName() {
		// Thread thread = new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		String appFilePath = Environment.getExternalStorageDirectory() + "/" + "AllShengMedical";
		String folderName = SharedPreferencesUtils.get(BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "") + "";
		String fileName = SharedPreferencesUtils.get(BaseApplication.getContext(),
				BaseApplication.FILEMANGER_PREPAREFILENAME, "") + "";

		String oldPath = appFilePath + "/" + folderName + "/" + fileName;

		// File file = new File(path + "/" + fileName)
		String newPath = "";
		if (stopByUser) {
			if(isHaveFourTemp){
				newPath = appFilePath + "/" + folderName + "/" + "_" + fileName;
			}else{
				newPath = appFilePath + "/" + folderName + "/" + "!" + fileName;
			}
			
		} else {

			newPath = appFilePath + "/" + folderName + "/" + "_" + fileName;
		}
		FileManagerUtil fileManagerUtil = new FileManagerUtil();
		fileManagerUtil.updateFileName(oldPath, newPath);

		// 读取
		List<FileBean> fileBeans2;
		SharedPreferences preferences = getSharedPreferences(BaseApplication.FILEMANGER_HISTORYARRAYLIST, MODE_PRIVATE);
		String json = preferences.getString("fileBean", null);
		fileBeans2 = new ArrayList<FileBean>();
		if (json != null) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<FileBean>>() {
			}.getType();

			fileBeans2 = gson.fromJson(json, type);
			for (int i = 0; i < fileBeans2.size(); i++) {
				Log.d("读sp", fileBeans2.get(i).getFoldName() + ":" + fileBeans2.get(i).getFileName() + ","
						+ fileBeans2.get(i).getCreateTime());
			}
		}

		if (stopByUser) {
			for (int i = 0; i < fileBeans2.size(); i++) {
				if (fileBeans2.get(i).getFoldName().equals(folderName)) {
					if (fileBeans2.get(i).getFileName().equals(fileName)) {
						fileBeans2.get(i).setFileName("!" + fileName);
					}
				}
			}
		} else {
			for (int i = 0; i < fileBeans2.size(); i++) {
				if (fileBeans2.get(i).getFoldName().equals(folderName)) {
					if (fileBeans2.get(i).getFileName().equals(fileName)) {
						fileBeans2.get(i).setFileName("_" + fileName);
					}
				}
			}

		}

		// 写
		SharedPreferences.Editor editor = getSharedPreferences(BaseApplication.FILEMANGER_HISTORYARRAYLIST,
				MODE_PRIVATE).edit();
		Gson gson = new Gson();
		String json2 = gson.toJson(fileBeans2);
		Log.d("gson写", "saved json is " + json2);
		editor.putString("fileBean", json2);
		editor.commit();

		SharedPreferencesUtils.put(BaseApplication.getContext(), BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
				folderName);
		if (stopByUser) {
			SharedPreferencesUtils.put(BaseApplication.getContext(), BaseApplication.FILEMANGER_PREPAREFILENAME,
					"!" + fileName);
			if(isHaveFourTemp){
				SharedPreferencesUtils.put(BaseApplication.getContext(), BaseApplication.FILEMANGER_PREPAREFILENAME,
						"_" + fileName);
			}else{
				SharedPreferencesUtils.put(BaseApplication.getContext(), BaseApplication.FILEMANGER_PREPAREFILENAME,
						"!" + fileName);
			}
		} else {

			SharedPreferencesUtils.put(BaseApplication.getContext(), BaseApplication.FILEMANGER_PREPAREFILENAME,
					"_" + fileName);
		}
		saveBoo = true;
	}

	// });
	// thread.start();
	// }

}
